package com.service.devimonitor;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.bpms.common.CommonUtil;
import com.bpms.common.JdbcWorker;
import com.bpms.common.VO;
import com.bpms.eai.PackTool;
import com.bpms.esb.IService;
import com.zk.atm.forms.AtmpDeviceStatusForm;
import com.zk.atm.forms.AtmpDeviceTypeForm;
import com.zk.atm.utils.AccessDBConnection;
import com.zk.atm.utils.EncryptUtil;
import com.zk.atm.utils.PrimaryKeyUtil;
import com.zk.atm.utils.StringUtil;
import com.zk.atm.vo.AtmpDeviceType;
import com.zk.atm.vo.AtmpDeviceTypeChildren;
import com.zk.atm.vo.BaseVo;

public class AtmpDeviceTypeImpl extends PackTool implements IService {
	private static final Logger logger=Logger.getLogger(AtmpDeviceTypeImpl.class);
	
	@Override
	public VO exec(VO arg0) {
		byte [] body = (byte[])arg0.getObj("body");
		try{	
			VO t =new VO();
			String m = this.getField(body, body.length, "m");
//			if(m.equals("saveDeviceType")){
				t.voType="ATM.savaDeviceType";
				String TYPE_ID = this.getField(body, body.length, "TYPE_ID");//机器编号
				String TYPE_CODE =this.getField(body, body.length, "TYPE_CODE");//机器
				String TYPE_NAME = this.getField(body, body.length, "TYPE_NAME");//机器名称
				String TIME_MARK = this.getField(body, body.length, "TIME_MARK");//时间
				t.setAttr("TYPE_ID", TYPE_ID);
				t.setAttr("TYPE_CODE", TYPE_CODE);
				t.setAttr("TYPE_NAME", TYPE_NAME);
				t.setAttr("TIME_MARK", TIME_MARK);
//			else{
			    JdbcWorker db=null;
			    String condition_sql="select *xxtype t where 1=1 ";
//			}
			
			CommonUtil.debug("0000");
			return t;
		}catch (Exception e) {
			CommonUtil.debug("9999");
			return null;
		}
	}

	public List<AtmpDeviceType> getDeviceTypeList(AtmpDeviceTypeForm form) 
	   throws Exception{
		List<AtmpDeviceType> list=new ArrayList();
		Connection conn=AccessDBConnection.getConnection();
		try {
			if(conn==null||conn.isClosed()){
				logger.error("获取conn失败!");
				return null;
			}
			String type_name=form.getDevice_type_vo().getType_name();
			String type_code=form.getDevice_type_vo().getType_code();
			//分页的sql
//			  select *from (
//					     select rownum as rn, adsc.* from atmp_device_status_current adsc where 1=1 
//					     ) adsc1
//					     where adsc1.rn>=6
//					     and rownum<10;
			String device_sql=" select *from atmp_device_type adt  where 1=1 ";

			if(!type_name.equals("")){
				device_sql+=" and adt.type_name like '%"+type_name+"%'";
			}
			if(!type_code.equals("")){
				device_sql+="  and adt.type_code like '%"+type_code+"%'";
			}
			System.out.println("**********************************sql="+device_sql);
			AtmpStatusCurrentReflect reflect=new AtmpStatusCurrentReflect();
			list=reflect.getListByClassName(device_sql, "com.zk.atm.vo.AtmpDeviceType");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			AccessDBConnection.closeConnection(conn);
		}
		return list;
	}
	
	public boolean saveAtmpDeviceType(AtmpDeviceTypeForm form) throws Exception{
		boolean is_success=false;
		try {
			AtmpDeviceType ad=form.getDevice_type_vo();
			String type_id=StringUtil.getPropertyValue(ad.getType_id());
			String table_name="atmp_device_type";
			JdbcWorker jdbc=new JdbcWorker();
			//把device里面的值,全部封装到bpmvo中
			VO vo=this.getAtmpVO(ad);
			String primary_column="type_id";
			//如果id为空,则表明是新增操作,则获取生成的主键,保存
			if(type_id.equals("")){
				String primary_key=PrimaryKeyUtil.getPrimaryKey(table_name, null);
				vo.setAttr(primary_column, primary_key);
			    vo.voType=table_name;
			    Date d=new Date();
			    vo.setAttr("time_mark",d.toLocaleString());
			    jdbc.insert(vo);
			    System.out.println("新增操作成功!");
			    is_success=true;
			}else{
				VO key_vo=new VO();
				key_vo.setAttr(primary_column, type_id);
				key_vo.keyString=primary_column;
				key_vo.voType=table_name;
				Date d=new Date();
				vo.setAttr("time_mark", d.toLocaleString());
				jdbc.update(vo, key_vo);
				System.out.println("更新操作成功!");
				is_success=true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return is_success;
	}
	
	protected VO getAtmpVO(BaseVo ad) throws Exception{
		VO vo=new VO();
		Field[] fields=ad.getClass().getDeclaredFields();
		 for (Field field : fields) {
				String field_name=field.getName();
				//System.out.println(field_name);
				String method_name=AtmpStatusCurrentReflect.getGetterMethod(field_name);
				if(method_name.equals("")){		
					continue;
				}
				Method m=null;
				try {	
					m=ad.getClass().getMethod(method_name);		
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
				if(m==null){
					continue;
				}
				String type_name=field.getType().getName().toString();
				Object value=null;
				if(type_name.equals("java.lang.String")){
					value=new String();
				    value=(String)m.invoke(ad);
				}else if(type_name.equals("java.lang.Long")){
					value=new Long(-1);
					value=m.invoke(ad);
				}else if(type_name.equals("java.util.Date")){
					value=new Date();
					value=m.invoke(ad);
				}else{
					value="";
				}
				if(value!=null){
					if(logger.isDebugEnabled()){
					  System.out.println("getAtmpVO:reflect:value="+value.toString());
					}
					vo.setObj(field_name, value);
				}
		  }
		 return vo;
	}

	public boolean checkTypeReferChildrenType(AtmpDeviceTypeForm form) throws Exception{
		String sql=  "  select count(*) as total from atmp_device_type adt,atmp_device_type_children adtc where 1=1 "
					+"	 and adt.type_id=adtc.type_id "
					+"	 and adt.type_id=?";
		String id=StringUtil.getPropertyValue(form.getDevice_type_vo().getType_id());
		if(id.equals("")){
			return false;
		}
		List list=new ArrayList();
		Connection conn=null;
		try {
			conn=AccessDBConnection.getConnection();
			PreparedStatement pst=conn.prepareStatement(sql);
			pst.setString(1, id);
			ResultSet rs=pst.executeQuery();
			while(rs.next()){
				String total=rs.getString("total");
				list.add(total);
			}
			if(list.size()>0){
				Integer number=new Integer(list.get(0).toString());
				return number>0?true:false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			AccessDBConnection.closeConnection(conn);
		}
		return false;
	}
	
	public boolean deleteDeviceTypeById(AtmpDeviceTypeForm form) throws Exception {
		String id=StringUtil.getPropertyValue(form.getDevice_type_vo().getType_id());
		if(id.equals("")){
			String msg="参数值:type_id为空,不能执行删除操作!";
			System.out.println(msg);
			logger.error("deleteDeviceTypeById:"+msg);
			return false;
		}
		String exec_sql="  delete from atmp_device_type adt  where 1=1 " +
				" and adt.type_id='"+id+"'";
		form.setExec_sql(exec_sql);
		return AtmpStatusCurrentReflect.executeSaveOrDelBySql(form);
	}
	
	/********************start 以下是type_children的列表,保存,删除的方法*****************************/
	public List<AtmpDeviceTypeChildren> getDeviceTypeChildrenList(AtmpDeviceTypeForm form) 
	   throws Exception{
		List<AtmpDeviceTypeChildren> list=new ArrayList();
		Connection conn=AccessDBConnection.getConnection();
		try {
			if(conn==null||conn.isClosed()){
				logger.error("获取conn失败!");
				return null;
			}
			String type_name=StringUtil.getPropertyValue(form.getDevice_type_children_vo().getStandby_column2());
			String type_code=StringUtil.getPropertyValue(form.getDevice_type_children_vo().getChild_device_code());
			//分页的sql
//			  select *from (
//					     select rownum as rn, adsc.* from atmp_device_status_current adsc where 1=1 
//					     ) adsc1
//					     where adsc1.rn>=6
//					     and rownum<10;
			String device_sql="  select adtc.*,adt.type_code,adt.type_name,bd.dictname as child_device_name_cn " 
					        +" from atmp_device_type_children adtc " 
					        +" left join atmp_device_type adt "
							+"	 on adtc.type_id=adt.type_id "
							+"	 left join bpm_dict bd "
							+"	 on lower(adtc.child_device_name) = lower(bd.dictid) "	
							+"	 where 1=1 ";

			if(!type_name.equals("")){
				device_sql+=" and lower(bd.dictname) like lower('%"+type_name+"%')";
			}
			if(!type_code.equals("")){
				device_sql+="  and adtc.child_device_code like '%"+type_code+"%'";
			}
			System.out.println("**********************************sql="+device_sql);
			AtmpStatusCurrentReflect reflect=new AtmpStatusCurrentReflect();
			list=reflect.getListByClassName(device_sql, "com.zk.atm.vo.AtmpDeviceTypeChildren");
			//对子设备名称加密
			List new_list=new ArrayList();
			for (Object object : list) {
				AtmpDeviceTypeChildren child_vo=(AtmpDeviceTypeChildren) object;
				String child_device_name_cn=StringUtil.getPropertyValue(child_vo.getStandby_column2());
				if(!child_device_name_cn.equals("")){
					child_vo.setStandby_column2(new String(EncryptUtil.decryptBASE64(child_device_name_cn)));
				}
				new_list.add(child_vo);
			}
			list=new_list;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			AccessDBConnection.closeConnection(conn);
		}
		return list;
	}
	
	public boolean saveAtmpDeviceTypeChildren(AtmpDeviceTypeForm form) throws Exception{
		boolean is_success=false;
		try {
			AtmpDeviceTypeChildren ad=form.getDevice_type_children_vo();
			String type_id=StringUtil.getPropertyValue(ad.getChildren_device_id());
			String table_name="atmp_device_type_children";
			JdbcWorker jdbc=new JdbcWorker();
			//把device里面的值,全部封装到bpmvo中
			VO vo=this.getAtmpVO(ad);
		    //加密设备名称
			String child_device_name_cn_key="standby_column2";
			String child_device_name_cn=StringUtil.getPropertyValue(vo.getAttr(child_device_name_cn_key));
			if(!child_device_name_cn.equals("")){
				child_device_name_cn=EncryptUtil.encryptBASE64(child_device_name_cn.getBytes());
				vo.setAttr(child_device_name_cn_key, child_device_name_cn);
			}
			String primary_column="children_device_id";
			//如果id为空,则表明是新增操作,则获取生成的主键,保存
			if(type_id.equals("")){
				String primary_key=PrimaryKeyUtil.getPrimaryKey(table_name, null);
				vo.setAttr(primary_column, primary_key);
			    vo.voType=table_name;
			    Date d=new Date();
			    vo.setAttr("time_mark",d.toLocaleString());
			    jdbc.insert(vo);
			    System.out.println("新增操作成功!");
			    is_success=true;
			}else{
				VO key_vo=new VO();
				key_vo.setAttr(primary_column, type_id);
				key_vo.keyString=primary_column;
				key_vo.voType=table_name;
				Date d=new Date();
				vo.setAttr("time_mark", d.toLocaleString());
				jdbc.update(vo, key_vo);
				System.out.println("更新操作成功!");
				is_success=true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return is_success;
	}
	
	public boolean deleteDeviceTypeChildrenById(AtmpDeviceTypeForm form) throws Exception {
		String id=StringUtil.getPropertyValue(form.getDevice_type_children_vo().getChildren_device_id());
		if(id.equals("")){
			String msg="参数值:type_id为空,不能执行删除操作!";
			System.out.println(msg);
			logger.error("deleteDeviceTypeChildrenById:"+msg);
			return false;
		}
		String exec_sql="  delete from atmp_device_type_children adt  where 1=1 " +
				" and adt.children_device_id='"+id+"'";
		form.setExec_sql(exec_sql);
		return AtmpStatusCurrentReflect.executeSaveOrDelBySql(form);
	}
	/********************end        type_children的列表,保存,删除的方法*****************************/

	public boolean checkChildrenReferStatusOriginal(AtmpDeviceTypeForm form) throws Exception {
		String sql= " select count(*) as total "
		 +" from atmp_device_type_children adtc, atmp_device_status_original adso "
		 +" where lower(adtc.child_device_name) =lower( adso.device_column_key) "
		 +"   and adtc.child_device_name = ?";
//			"   select count(*) as total from atmp_device_type_children adtc,atmp_device_status_original adso "
//					 +" where adtc.standby_column1=adso.device_column_key "
//					 +" and  (adtc.standby_column1=? or adtc.children_device_id=?)";
			String child_device_name_en=StringUtil.getPropertyValue(form.getDevice_type_children_vo().getStandby_column1());
			String id=StringUtil.getPropertyValue(form.getDevice_type_children_vo().getChildren_device_id());
			if(id.equals("")){
				return false;
			}
			List list=new ArrayList();
			Connection conn=null;
			try {
				conn=AccessDBConnection.getConnection();
				PreparedStatement pst=conn.prepareStatement(sql);
				pst.setString(1, child_device_name_en);
				//pst.setString(2, id);
				ResultSet rs=pst.executeQuery();
				while(rs.next()){
					String total=rs.getString("total");
					list.add(total);
				}
				if(list.size()>0){
					Integer number=new Integer(list.get(0).toString());
					return number>0?true:false;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				AccessDBConnection.closeConnection(conn);
			}
			return false;
		}
}
